package com.qiguliuxing.dts.wx.controller;

import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.constant.RedisKeyConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.LoginUser;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.manager.HomeCacheManager;
import com.qiguliuxing.dts.db.domain.DtsCategory;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import com.qiguliuxing.dts.service.base.*;
import com.qiguliuxing.dts.service.seckill.WxSeckillService;
import com.qiguliuxing.dts.service.system.SystemConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 首页服务
 */
@RestController
@RequestMapping("/wx/home")
@Validated
@Api(tags = "首页服务")
public class WxHomeController {
    private static final Logger logger = LoggerFactory.getLogger(WxHomeController.class);

    @Autowired
    private DtsAdService adService;

    @Autowired
    private DtsGoodsService goodsService;

    @Autowired
    private DtsBrandService brandService;

    @Autowired
    private DtsTopicService topicService;

    @Autowired
    private DtsCategoryService categoryService;

    @Autowired
    private DtsGrouponRulesService grouponRulesService;

    @Autowired
    private DtsCouponService couponService;

    @Autowired
    private DtsArticleService articleService;

    @Autowired
    private WxSeckillService wxSeckillService;

    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(9, 9, 1000, TimeUnit.MILLISECONDS,
            WORK_QUEUE, HANDLER);

    @ApiOperation(value = "清除缓存")
    @GetMapping("/cache")
    @WebLog(description = "清除缓存")
    public Object cache(@ApiParam(value = "标识") @NotNull String key) {
        if (!"Dts_cache".equals(key)) {
            logger.error("缓存已清除出错:非本平台标识！！！");
            return ResponseUtils.fail();
        }
        // 清除缓存
        HomeCacheManager.clearAll();
        return ResponseUtils.ok("缓存已清除");
    }

    /**
     * 首页数据
     *
     * @param userId 当用户已经登录时，非空。为登录状态为null
     * @return 首页数据
     */
    @GetMapping("/index")
    @ApiOperation(value = "首页数据")
    @WebLog(description = "首页数据", excludes = {LogParamsConsts.RESPONSE})
    public Object index(@LoginUser Integer userId) {
        Map<String, Object> data = new HashMap<String, Object>();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 先查询和用户有关的信息
        Callable<List> couponListCallable;
        try {
            if (userId == null) {// 调整，用户未登录，不发送优惠券
                couponListCallable = () -> couponService.queryList(0, 3);
            } else {
                couponListCallable = () -> couponService.queryAvailableList(userId, 0, 3);
            }
            FutureTask<List> couponListTask = new FutureTask<>(couponListCallable);
            executorService.submit(couponListTask);

            // 优先从缓存中读取
            if (HomeCacheManager.hasData(RedisKeyConsts.HOME_CACHE_INDEX)) {
                data = HomeCacheManager.getCacheData(RedisKeyConsts.HOME_CACHE_INDEX);
                if (data != null) {// 加上这个判断，排除判断后到获取数据之间时间段清理的情况
                    data.put("seckillGoodsList", wxSeckillService.getCurrBatchSeckillGood(userId, 0, SystemConfig.getSeckillLimit()));// 秒杀数据取秒杀批次数据
                    data.put("couponList", couponListTask.get());
                    return ResponseUtils.ok(data);
                }
            }

            Callable<List> bannerListCallable = () -> adService.queryIndex();

            Callable<List> articleListCallable = () -> articleService.queryList(0, 5, "add_time", "desc");

            Callable<List> channelListCallable = () -> categoryService.queryChannel();

            Callable<List> newGoodsListCallable = () -> goodsService.queryByNew(0, SystemConfig.getNewLimit());

            Callable<List> hotGoodsListCallable = () -> goodsService.queryByHot(0, SystemConfig.getHotLimit());

            Callable<List> brandListCallable = () -> brandService.queryVO(0, SystemConfig.getBrandLimit());

            Callable<List> topicListCallable = () -> topicService.queryList(0, SystemConfig.getTopicLimit());

            // 团购专区
            Callable<List> grouponListCallable = () -> grouponRulesService.queryList(0, 6);

            Callable<List> floorGoodsListCallable = this::getCategoryList;

            FutureTask<List> bannerTask = new FutureTask<>(bannerListCallable);
            FutureTask<List> articleTask = new FutureTask<>(articleListCallable);
            FutureTask<List> channelTask = new FutureTask<>(channelListCallable);
            FutureTask<List> newGoodsListTask = new FutureTask<>(newGoodsListCallable);
            FutureTask<List> hotGoodsListTask = new FutureTask<>(hotGoodsListCallable);
            FutureTask<List> brandListTask = new FutureTask<>(brandListCallable);
            FutureTask<List> topicListTask = new FutureTask<>(topicListCallable);
            FutureTask<List> grouponListTask = new FutureTask<>(grouponListCallable);
            FutureTask<List> floorGoodsListTask = new FutureTask<>(floorGoodsListCallable);
            executorService.submit(bannerTask);
            executorService.submit(articleTask);
            executorService.submit(channelTask);
            executorService.submit(newGoodsListTask);
            executorService.submit(hotGoodsListTask);
            executorService.submit(brandListTask);
            executorService.submit(topicListTask);
            executorService.submit(grouponListTask);
            executorService.submit(floorGoodsListTask);

            data.put("banner", bannerTask.get());
            data.put("articles", articleTask.get());
            data.put("channel", channelTask.get());
            data.put("couponList", couponListTask.get());
            data.put("newGoodsList", newGoodsListTask.get());
            data.put("hotGoodsList", hotGoodsListTask.get());
            data.put("brandList", brandListTask.get());
            data.put("topicList", topicListTask.get());
            data.put("grouponList", grouponListTask.get());
            data.put("floorGoodsList", floorGoodsListTask.get());
            data.put("seckillGoodsList", wxSeckillService.getCurrBatchSeckillGood(userId,0, SystemConfig.getSeckillLimit()));
            // 缓存数据首页缓存数据
            HomeCacheManager.loadData(RedisKeyConsts.HOME_CACHE_INDEX, data);
            executorService.shutdown();

        } catch (Exception e) {
            logger.error("首页信息获取失败：{}", e.getMessage());
            e.printStackTrace();
        }

        return ResponseUtils.ok(data);
    }

    private List<Map> getCategoryList() {
        List<Map> categoryList = new ArrayList<>();
        List<DtsCategory> catL1List = categoryService.queryL1WithoutRecommend(0, SystemConfig.getCatlogListLimit());
        for (DtsCategory catL1 : catL1List) {
            List<DtsCategory> catL2List = categoryService.queryByPid(catL1.getId());
            List<Integer> l2List = new ArrayList<>();
            for (DtsCategory catL2 : catL2List) {
                l2List.add(catL2.getId());
            }

            List<DtsGoods> categoryGoods;
            if (l2List.size() == 0) {
                categoryGoods = new ArrayList<>();
            } else {
                categoryGoods = goodsService.queryByCategory(l2List, 0, SystemConfig.getCatlogMoreLimit());
            }

            Map<String, Object> catGoods = new HashMap<>();
            catGoods.put("id", catL1.getId());
            catGoods.put("name", catL1.getName());
            catGoods.put("goodsList", categoryGoods);
            categoryList.add(catGoods);
        }
        return categoryList;
    }
}